package tun

import (
	"log"
	"syscall"
	"unsafe"
)

const (
	TUNDevice byte = 0
	TAPDevice byte = 1
)

var (
	MTU uint32
)

type Tun struct {
	FD int
}

func init() {
	var err error
	if MTU, err = GetMTU("tun0"); err != nil {
		log.Fatal(err)
	}
}

func NewTunDevice(name string, device byte) (*Tun, error) {
	var fd int
	var err error
	if device == TUNDevice {
		fd, err = OpenTUN(name)
	} else {
		fd, err = OpenTAP(name)
	}
	tun := Tun{
		FD: fd,
	}
	return &tun, err
}

// OpenTUN opens the specified TUN device, sets it to non-blocking mode, and
// returns its file descriptor.
func OpenTUN(name string) (int, error) {
	return open(name, syscall.IFF_TUN|syscall.IFF_NO_PI)
}

// OpenTAP opens the specified TAP device, sets it to non-blocking mode, and
// returns its file descriptor.
func OpenTAP(name string) (int, error) {
	return open(name, syscall.IFF_TAP|syscall.IFF_NO_PI)
}

func open(name string, flags uint16) (int, error) {
	fd, err := syscall.Open("/dev/net/tun", syscall.O_RDWR, 0)
	if err != nil {
		return -1, err
	}

	var ifr struct {
		name  [16]byte
		flags uint16
		_     [22]byte
	}

	copy(ifr.name[:], name)
	ifr.flags = flags
	_, _, errno := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), syscall.TUNSETIFF, uintptr(unsafe.Pointer(&ifr)))
	if errno != 0 {
		_ = syscall.Close(fd)
		return -1, errno
	}

	// if err = syscall.SetNonblock(fd, true); err != nil {
	// 	syscall.Close(fd)
	// 	return -1, err
	// }

	return fd, nil
}

func Read(fd int) ([]byte, error) {
	var buff = make([]byte, MTU)
	n, err := syscall.Read(fd, buff)
	if n <= 0 || err != nil {
		return nil, err
	}
	return buff, err
}

func Write(fd int, buff []byte) error {
	correctBuff := make([]byte, len(buff))
	copy(correctBuff, buff)
	n, err := syscall.Write(fd, correctBuff)
	if n <= 0 || err != nil {
		return err
	}
	return nil
}

// GetMTU determines the MTU of a network interface device.
func GetMTU(name string) (uint32, error) {
	fd, err := syscall.Socket(syscall.AF_UNIX, syscall.SOCK_DGRAM, 0)
	if err != nil {
		return 0, err
	}

	defer func() {
		_ = syscall.Close(fd)
	}()

	var ifreq struct {
		name [16]byte
		mtu  int32
		_    [20]byte
	}

	copy(ifreq.name[:], name)
	_, _, errno := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), syscall.SIOCGIFMTU, uintptr(unsafe.Pointer(&ifreq)))
	if errno != 0 {
		return 0, errno
	}

	return uint32(ifreq.mtu), nil
}
